#include "Inf_W5500_Ping.h"
#include "spi.h"
#include "gpio.h"



void Inf_W5500_Ping_Init(void)
{
    /*1.��W5500ע��ײ㺯��*/
    //user_register_function();   
    w5500_wiznet_register();
    //w5500_restart();
	  //网络配置暂时不用，其他地方已经设置
    //w5500_setnetinfo();

	
}


void __w5500_spi_cris_enter(void)
{
    __set_PRIMASK(1);
}
void __w5500_spi_cris_exit(void)
{
    __set_PRIMASK(0);
}

static void __w5500_spi_cs_select(void) {
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_RESET);
}

static void __w5500_spi_cs_deselect(void) {
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_SET);
}

static void __w5500_spi_read_buffer(uint8_t *buff, uint16_t len) {
	HAL_SPI_Receive(&hspi2, buff, len, HAL_MAX_DELAY);
}

static void __w5500_spi_write_buffer(uint8_t *buff, uint16_t len) {
	HAL_SPI_Transmit(&hspi2, buff, len, HAL_MAX_DELAY);
}

static uint8_t __w5500_read_byte(void) {
	uint8_t byte;
	__w5500_spi_read_buffer(&byte, sizeof(byte));
	return byte;
}

static void __w5500_write_byte(uint8_t byte) {
	__w5500_spi_write_buffer(&byte, sizeof(byte));
}


void w5500_wiznet_register(void) {
// First of all, Should register SPI callback functions implemented by user for accessing WIZCHIP
	/* Critical section callback */
	//注册临界区函数
	reg_wizchip_cris_cbfunc(__w5500_spi_cris_enter, __w5500_spi_cris_exit);   //???????
	/* Chip selection call back */
	//注册SPI片选信号函数
	reg_wizchip_cs_cbfunc(__w5500_spi_cs_select, __w5500_spi_cs_deselect); //??SPI??��???
	/* SPI Read & Write callback function */
	//注册读写函数
	reg_wizchip_spi_cbfunc(__w5500_read_byte, __w5500_write_byte);    //???��??

	return;
}



uint8_t mac[] = {0x00, 0x08, 0xdc, 0x12, 0x34, 0x56};
uint8_t ip[] = {192, 168, 2, 199};
uint8_t gw[] = {192, 168, 2, 1};
uint8_t sn[] = {255, 255, 255, 0};
//uint8_t dns[] = {8, 8, 8, 8};

void w5500_restart(void) {
	//HAL_GPIO_WritePin(SPI2_CS0_GPIO_Port, SPI2_CS0_Pin, GPIO_PIN_RESET);
	__w5500_spi_cs_select();
	HAL_Delay(1);  // delay 1ms
	//HAL_GPIO_WritePin(SPI2_CS0_GPIO_Port, SPI2_CS0_Pin, GPIO_PIN_SET);
	__w5500_spi_cs_deselect();
	HAL_Delay(1600);  // delay 1600ms
	printf("w5500 restarted\r\n");
}

void w5500_setnetinfo(void)
{
    setSHAR(mac);
    setSIPR(ip);
    setGAR(gw);
    setSUBR(sn);
    //setDNS(dns);
    printf("w5500 set netinfo ok\r\n");
}

//完成 W5500 芯片的初始化配置，包括内存分配和基本硬件检测
void w5500_wiznet_chip_config(void) {
	uint8_t memsize[2][8] = { { 2, 2, 2, 2, 2, 2, 2, 2 }, { 2, 2, 2, 2, 2, 2, 2,
			2 } };

	//WIZCHIP 执行芯片控制操作
	if (ctlwizchip(CW_INIT_WIZCHIP, (void*) memsize) == -1) {
		printf("WIZCHIP Initialized fail.\r\n");
		while (1)
			;
	}
	printf("w5500 chip configured\r\n");
}



